<template>
	<view title="分类" tabbar="/pages/index/category" :bgStyle="{ color: '#fff' }">
		<view class="search" :style="{ height: `${statusBarHeight}px`}"></view>
		<uv-navbar leftIcon="" title="分类"></uv-navbar>
				<!-- 搜索栏 -->
		<view class="search-wrap" @click="hanldeSearch">
			<uv-search disabled height="70rpx" shape="square"  placeholderColor="#C4C4C4" bgColor="#F7F7F7"  placeholder="请输入搜索内容" :showAction="false"></uv-search>
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 左侧分类菜单 -->
			<view class="side-menu-wrap" :style="[{ top: Number(statusBarHeight + 88 + 80) + 'rpx' }]">
				<scroll-view scroll-y :style="[{ height: pageHeight - 80 + 'px' }]">
					<view class="menu-item ss-flex" 
						v-for="(item, index) in state.categoryList?.children"
						:key="item.id" 
						:class="[{ 'menu-item-active': index == state.activeMenu }]"
						@tap="onMenu(index)">
						<view class="menu-title ss-line-1">
							{{ item.name }}
						</view>
					</view>
				</scroll-view>
			</view>
			
			<!-- 右侧商品列表 -->
			<view class="goods-list-box" v-if="state.categoryList?.children?.length">
				<!-- 商品列表 -->
				<view class="goods-container">
					<template>
						<first-one v-if="state.categoryList.style === 'first_one'" :data="state.categoryList"
							:activeMenu="state.activeMenu" :pagination="state.pagination" @goodsClick="handleGoodsClick" />
						<first-two v-if="state.categoryList.style === 'first_two'" :data="state.categoryList"
							:activeMenu="state.activeMenu" :pagination="state.pagination" @goodsClick="handleGoodsClick" @showAddCart="showSku" />
						<second-one v-if="state.categoryList.style === 'second_one'" :data="state.categoryList"
							:activeMenu="state.activeMenu" :pagination="state.pagination" @goodsClick="handleGoodsClick" @showSku="showSku" />
						<third-one v-if="state.categoryList.style === 'third_one'" :data="state.categoryList"
							:activeMenu="state.activeMenu" :pagination="state.pagination" />
					</template>
				</view>

				<!-- 加载更多 -->
				<uni-load-more v-if="
					(state.categoryList.style === 'first_one' ||
					state.categoryList.style === 'first_two') &&
					state.pagination.total > 0
				" :status="state.loadStatus" :content-text="{
					contentdown: '点击查看更多',
				}" @tap="loadmore" />
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state" v-if="!state.categoryList?.children?.length">
				<image src="/static/cart-empty.png" mode="aspectFit" class="empty-img"></image>
				<text class="empty-text">暂无分类数据</text>
			</view>
		</view>

		<!-- SKU规格选择弹框 - 使用商品详情页面样式，只显示加购按钮 -->
		<s-select-sku
			v-if="state.showSku"
			:isScore="false"
			:isGift="0"
			:isCategoryPage="true"
			:goodsInfo="state.skuData"
			:userInfo="state.userInfo"
			:show="state.showSku"
			@addCart="onAddCart"
			@buy="onBuy"
			@change="onSkuChange"
			@close="handleSkuClose" />


		
	</view>
</template>

<script setup>
	import secondOne from './components/second-one.vue';
	import thirdOne from './components/third-one.vue';
	import firstOne from './components/first-one.vue';
	import firstTwo from './components/first-two.vue';
	import sheep from '@/sheep';

	import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app';
	import { reactive, computed, onMounted } from 'vue';
	import _ from 'lodash';


	uni.showTabBar({
	  fail: () => {},
	});
	const state = reactive({
		categoryList: [],
		activeMenu: '0',
		searchKeyword: '', // 搜索关键词

		pagination: {
			data: [],
			current_page: 1,
			total: 1,
			last_page: 1,
		},
		loadStatus: '',
		// SKU相关状态
		showSku: false,
		skuData: {
			goodsInfo: null,
			goodsId: 0,
			isGift: 0
		},
		userInfo: {},
	});

	const { screenHeight, safeAreaInsets, screenWidth, safeArea } = sheep.$platform.device;
	const pageHeight = computed(() => safeArea.height - 44 - 50);
	const statusBarHeight = sheep.$platform.device.statusBarHeight * 2;



	async function getList(options) {
		try {
			const { code, data } = await sheep.$api.category.list({
				id:9|| '',
			});
			if (code === 1) {
				state.categoryList = data;
				uni.$on('templateClick', (name, index) => {
					state.activeMenu = index
				})
			} else {
				console.log('加载分类失败:', data?.msg || '未知错误')
				state.categoryList = { children: [] }
			}
		} catch (error) {
			console.log('分类加载异常:', error)
			state.categoryList = { children: [] }
		}
	}
	const hanldeSearch=()=>{
		// 检查登录状态
		// if (!checkLoginStatus()) {
		// 	return
		// }
		uni.navigateTo({
			url:'/subPackages/search/search'
		})
	}

	// 处理商品点击
	const handleGoodsClick = (item) => {
		// 检查登录状态
		// if (!checkLoginStatus()) {
		// 	return
		// }
		// 跳转到商品详情页
		sheep.$router.go('/subPackages/goods/index', { id: item.id })
	}



	const onMenu = (val) => {
		// 检查登录状态
		// if (!checkLoginStatus()) {
		// 	return
		// }
		state.activeMenu = val;
		if (state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two') {
			state.pagination = {
				data: [],
				current_page: 1,
				total: 1,
				last_page: 1,
			};
			getGoodsList(state.categoryList.children[val].id);
		}
	};

	async function getGoodsList(id, page = 1, list_rows = 6) {
		try {
			state.loadStatus = 'loading';
			const res = await sheep.$api.goods.list({
				category_id: id,
				list_rows,
				page,
				keyword: state.searchKeyword, // 添加搜索关键词
			});
			if (res.code === 1) {
				let couponList = _.concat(state.pagination.data, res.data.data);
				state.pagination = {
					...res.data,
					data: couponList,
				};
				if (state.pagination.current_page < state.pagination.last_page) {
					state.loadStatus = 'more';
				} else {
					state.loadStatus = 'noMore';
				}
			} else {
				console.log('加载商品列表失败:', res?.data?.msg || '未知错误')
				state.loadStatus = 'noMore';
			}
		} catch (error) {
			console.log('商品列表加载异常:', error)
			state.loadStatus = 'noMore';
		}
	}
	
	// 搜索处理
	const handleSearch = () => {
		if (state.categoryList.children?.length) {
			state.pagination = {
				data: [],
				current_page: 1,
				total: 1,
				last_page: 1,
			};
			getGoodsList(state.categoryList.children[state.activeMenu].id, 1);
		}
	}
	
	// 清除搜索
	const handleClearSearch = () => {
		state.searchKeyword = '';
		if (state.categoryList.children?.length) {
			state.pagination = {
				data: [],
				current_page: 1,
				total: 1,
				last_page: 1,
			};
			getGoodsList(state.categoryList.children[state.activeMenu].id, 1);
		}
	}
	
	// 加载更多
	function loadmore() {
		// 检查登录状态
		// if (!checkLoginStatus()) {
		// 	return
		// }
		if (
			state.loadStatus !== 'noMore' &&
			(state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two')
		) {
			getGoodsList(
				state.categoryList.children[state.activeMenu].id,
				state.pagination.current_page + 1,
			);
		}
	}
	
	// 获取用户信息
	const getUserInfo = async () => {
		try {
			// 检查是否已登录
			const isLogin = sheep.$store('user').isLogin;
			if (isLogin) {
				const userInfo = await sheep.$store('user').getInfo();
				state.userInfo = userInfo || {};
				console.log('分类页面获取到用户信息:', state.userInfo);
			} else {
				// 未登录时设置默认值
				state.userInfo = {
					level: 0,
					level_text: '普通用户'
				};
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			// 出错时设置默认值
			state.userInfo = {
				level: 0,
				level_text: '普通用户'
			};
		}
	};

	onLoad(async (options) => {
		// 获取用户信息
		await getUserInfo();
		
		await getList(options);

		if (state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two') {
			if (state.categoryList.children?.length) {
				getGoodsList(state.categoryList.children[0].id);
			}
		}
	});
	
	onReachBottom(() => {
		loadmore();
	});

	// 监听页面显示，更新用户信息
	onShow(() => {
		getUserInfo();
	});

	// SKU相关函数
	// 显示SKU弹框
	const showSku = (data) => {
		// 直接使用传递的商品信息
		state.skuData = data.goodsInfo;
		state.showSku = true;
	};

	// 添加购物车
	const onAddCart = (e) => {
		console.log('分类页面onAddCart被调用，接收到的数据:', e);

		// 检查登录状态
		const isLogin = sheep.$store('user').isLogin;
		if (!isLogin) {
			uni.showModal({
				title: '温馨提示',
				content: '添加购物车请先登录',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return
		}

	// SKU组件已经处理了规格选择和库存验证，这里直接处理加购逻辑
	// 传递完整的4个参数给购物车
	const cartData = {
		goods_id: e.goods_id, // 商品ID
		goods_num: e.goods_num || 1,
		goods_sku_price_id: e.goods_sku_price_id || e.id, // SKU价格ID
		type: "inc"
	};
	
	console.log('分类页面 - SKU组件传递的完整对象 e:', JSON.stringify(e));
	console.log('分类页面 - e.goods_sku_price_id:', e.goods_sku_price_id);
	console.log('分类页面 - e.id 的值:', e.id);
	console.log('分类页面 - e.goods_id 的值:', e.goods_id);

	console.log('分类页面SKU传递的数据:', e);
	console.log('分类页面添加购物车数据:', cartData);

		// 添加购物车成功后关闭SKU弹框
		sheep.$store('cart').add(cartData);

		uni.showToast({
			title: '加购成功',
			icon: 'success',
			success: () => {
				// 关闭弹框
				state.showSku = false;
			}
		});
	};

	// 立即购买
	const onBuy = (e) => {
		// 检查登录状态
		const isLogin = sheep.$store('user').isLogin;
		if (!isLogin) {
			uni.showModal({
				title: '温馨提示',
				content: '立即购买请先登录',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return
		}

	// SKU组件已经处理了规格选择和库存验证，这里直接处理购买逻辑
	// 立即购买 - 跳转到订单确认页
	sheep.$router.go('/subPackages/order/confirm', {
		data: JSON.stringify({
			order_type: 'goods',
			is_gift: '0',
			goods_list: [{
				goods_id: e.goods_id,
				goods_num: e.goods_num,
				goods_sku_price_id: e.goods_sku_price_id || e.id,
			}, ],
		}),
	});
	};

	// SKU变更
	const onSkuChange = (e) => {
		// 可按需处理SKU变更
	};

	// 处理SKU弹框关闭
	const handleSkuClose = () => {
		state.showSku = false;
	};


</script>

<style lang="scss" scoped>
	.search {
		background: #fff;
	}
	.search-wrap {
	width:100%;
	box-sizing:border-box;
	padding:10rpx 20rpx 20rpx;
	background: #fff;
	position: fixed;

	z-index:999;
	.search-input-wrap {
		background: #f8f8f8;
		border-radius: 40rpx;
		padding: 0 20rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
	}
}

	// 未登录提示样式
	.login-notice {
		margin: 20rpx;
		padding: 24rpx;
		background: linear-gradient(135deg, #fff7ed 0%, #fef3c7 100%);
		border-radius: 16rpx;
		border: 2rpx solid #fed7aa;
		box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.1);

		.notice-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 16rpx;

			.notice-icon {
				font-size: 32rpx;
				min-width: 40rpx;
			}

			.notice-text {
				flex: 1;
				font-size: 26rpx;
				color: #ea580c;
				line-height: 1.4;
				font-weight: 500;
			}

			.notice-btn {
				padding: 12rpx 24rpx;
				background: linear-gradient(135deg, #FF7C00 0%, #FF9500 100%);
				border-radius: 20rpx;
				font-size: 24rpx;
				color: white;
				font-weight: 600;
				white-space: nowrap;

				&:active {
					transform: scale(0.95);
				}
			}
		}
	}

.login-tip {
	margin: 20rpx;
	padding: 20rpx;
	background: #f0f8ff;
	border-radius: 16rpx;
	border: 1rpx solid #e6f3ff;

	.tip-content {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;

		text {
			font-size: 26rpx;
			color: #666;
		}
	}
}
	
	.main-content {
		display: flex;
		background: #f5f5f5;
		min-height: calc(100vh - 88rpx - 80rpx);
		position: relative;
	}
	
	.side-menu-wrap {
		width: 200rpx;
		height: 100%;
		background-color: #fff;
		position: fixed;
		left: 0;
		z-index: 100;

		.menu-item {
			width: 100%;
			height: 88rpx;
			position: relative;
			transition: all linear 0.2s;

			.menu-title {
				line-height: 32rpx;
				font-size: 28rpx;
				font-weight: 400;
				color: #333;
				margin-left: 28rpx;
				position: relative;
				z-index: 0;
			}

			&.menu-item-active {
				background: #F8F9FD;

				&::before {
					display: inline-block;
					width: 8rpx;
					height: 60rpx;
					background: #FF7C00;
					content: '';
					position: absolute;
					top: 15rpx;
					left: 0;
				}

				.menu-title {
					font-weight: 600;
					color: #FF7C00;
				}
			}
		}
	}

	.goods-list-box {
		background-color: #fff;
		width: calc(100vw - 200rpx);
		margin-left: 200rpx;
		min-height: calc(100vh - 88rpx - 80rpx);
		overflow-y:scroll;
		.category-title {
			padding: 30rpx 20rpx 20rpx;
			border-bottom: 1rpx solid #f0f0f0;
			
			.title-text {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.goods-count {
				font-size: 24rpx;
				color: #999;
				margin-left: 10rpx;
			}
		}
		
		.goods-container {
			padding: 20rpx;
			background: #fff;
			margin-top:80rpx;
		}
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 40rpx;
		width: calc(100vw - 200rpx);
		margin-left: 200rpx;
		background: #fff;

		.empty-img {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
</style>